#!/bin/bash

# 模块测试启动脚本
# 对所有解耦模块进行单独测试并记录结果

echo "🧪 开始运行模块测试..."
echo "=================================="

# 检查Python环境
if ! command -v python3 &> /dev/null; then
    echo "❌ Python3 未安装"
    exit 1
fi

# 创建测试目录
echo "📁 创建测试目录..."
mkdir -p hai-optimization/tests
mkdir -p hai-optimization/tests/logs

# 设置环境变量
export PYTHONPATH="/home/ubuntu/PhotoEnhanceAI-web:$PYTHONPATH"

# 进入测试目录
cd /home/ubuntu/PhotoEnhanceAI-web/hai-optimization/tests

echo "🔍 检查测试环境..."
echo "   Python版本: $(python3 --version)"
echo "   工作目录: $(pwd)"
echo "   Python路径: $PYTHONPATH"

# 检查必要的Python包
echo "📦 检查依赖包..."
python3 -c "
import sys
required_modules = [
    'asyncio', 'logging', 'time', 'json', 'sys', 'traceback', 
    'datetime', 'dataclasses', 'enum', 'typing', 'pathlib'
]
missing_modules = []
for module in required_modules:
    try:
        __import__(module)
    except ImportError:
        missing_modules.append(module)

if missing_modules:
    print(f'❌ 缺少模块: {missing_modules}')
    sys.exit(1)
else:
    print('✅ 基础依赖检查通过')
"

if [ $? -ne 0 ]; then
    echo "❌ 依赖检查失败"
    exit 1
fi

# 检查可选依赖
echo "🔍 检查可选依赖..."
python3 -c "
optional_modules = {
    'cryptography': 'mTLS和密钥管理功能',
    'aiohttp': 'HTTP客户端功能',
    'aioredis': 'Redis连接功能',
    'etcd3': 'etcd连接功能'
}

for module, description in optional_modules.items():
    try:
        __import__(module)
        print(f'✅ {module}: {description}')
    except ImportError:
        print(f'⚠️  {module}: {description} (未安装，相关功能可能不可用)')
"

echo ""
echo "🚀 开始运行所有模块测试..."
echo "=================================="

# 运行测试
python3 run_all_tests.py
test_result=$?

echo ""
echo "=================================="

if [ $test_result -eq 0 ]; then
    echo "🎉 所有测试完成！"
    echo ""
    echo "📋 测试覆盖的模块:"
    echo "   P1模块 (事件驱动强化、分布式追踪、状态管理抽象):"
    echo "     ✅ EventBus - 事件总线"
    echo "     ✅ ResultAggregator - 结果聚合器"
    echo "     ✅ WebhookNotificationSystem - Webhook通知系统"
    echo "     ✅ DistributedTracing - 分布式追踪"
    echo "     ✅ LatencyMonitor - 延迟监控"
    echo "     ✅ RedisStateStorage - Redis状态存储"
    echo "     ✅ EtcdStateStorage - etcd状态存储"
    echo ""
    echo "   P2模块 (容错降级、安全加固、灰度发布):"
    echo "     ✅ CircuitBreaker - 熔断器"
    echo "     ✅ DegradationManager - 降级策略管理器"
    echo "     ✅ FallbackManager - 兜底机制管理器"
    echo "     ✅ MTLSManager - 双向认证管理器"
    echo "     ✅ KeyManager - 密钥管理器"
    echo "     ✅ FeatureFlagManager - 功能开关管理器"
    echo "     ✅ ConfigAuditManager - 配置审计管理器"
    echo "     ✅ VersionManager - 版本管理器"
    echo "     ✅ RateLimiter - 速率限制器"
    echo ""
    echo "📊 测试结果文件:"
    echo "   • 详细报告: test_report_*.json"
    echo "   • 测试日志: all_tests_results.log"
    echo "   • 模块日志: test_results.log"
else
    echo "❌ 部分测试失败，请检查测试报告"
    echo ""
    echo "📊 测试结果文件:"
    echo "   • 详细报告: test_report_*.json"
    echo "   • 测试日志: all_tests_results.log"
    echo "   • 模块日志: test_results.log"
fi

echo "=================================="
echo "🔧 如需重新运行测试:"
echo "   cd /home/ubuntu/PhotoEnhanceAI-web/hai-optimization/tests"
echo "   python3 run_all_tests.py"
echo "=================================="

exit $test_result
